﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using PNProject.Core;
using PNProject.Core.Converter;
using PNProject.Models;
using PNProject.EF;

namespace PNProject.Controllers
{
    [Authorize(Roles = "SuperAdmin, Censor, Admin")]
    public class AdminArticleController : Controller
    {
        //
        // GET: /AdminArticle/

        public ActionResult Index(string page)
        {
            PagingNews contract = new PagingNews();
            contract.Content = new List<NewsModel>();
            int newspage;

            try
            {
                newspage = int.Parse(page);
            }
            catch (Exception e)
            {
                newspage = 1;
            }
            var count = StaticData.newsRepo.GetSome(a => a.CType == 1).Count();
            contract.TotalItem = count;
            var listNews = StaticData.newsRepo.GetSome(a => a.CType == 1, Information.NumberOfItemOnAdminPage, (newspage - 1) * Information.NumberOfItemOnAdminPage);
            contract.ListPages = PNLibraries.GetShowedPage(count, newspage, 10, 5);
            foreach (var item in listNews)
            {
                var conv = NewsConverter.NewsTo(item);
                conv.CreateDate = PNLibraries.PNTimeFormat(item.CreateDate.Value, false, true);
                contract.Content.Add(conv);
            }
            contract.NewsType = 0;
            contract.ActivePage = newspage;
            return View(contract);
        }

        public ActionResult Create()
        {
            return View(new NewsModel());
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Create(NewsModel model, HttpPostedFileBase file, HttpPostedFileBase attach)
        {
            var obj = NewsConverter.ToNews(model);
            obj.NewsID = Guid.NewGuid();
            obj.CreateDate = DateTime.Now;
            obj.CreateBy = Membership.GetUser().UserName;
            obj.ViewCount = 0;
            obj.Lang = model.Lang;
            obj.CType = 1;
            obj.CommentAllow = model.CommentAllow;
            obj.IsChecked = false;
            obj.TLink = PNLibraries.PNChuyenKhongDau(model.Title);
            if (string.IsNullOrEmpty(model.Avatar))
            {
                if (file != null)
                {
                    var legal = file.ContentType == "image/jpeg" || file.ContentType == "image/png" || file.ContentType == "image/gif" || file.ContentType == "image/jpg";
                    if (legal)
                    {
                        string time = PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                        string newName = time + "-" + file.FileName;
                        string path = "/Application_Data/Images/NewsImages/";
                        ServerHelper.SaveFileBaseOnServer(path, file, newName);
                        obj.Avatar = path + newName;
                    }
                }
            }
            else
            {
                obj.Avatar = model.Avatar;
            }
            if (attach != null)
            {
                string time = "pnco-" + PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                string newName = time + "-" + attach.FileName;
                string path = "/Application_Data/Files/NewsAttach/";
                ServerHelper.SaveFileBaseOnServer(path, attach, newName);
                obj.AttachFiles = path + newName + "*$*";
            }

            StaticData.newsRepo.Save(null, obj);
            return RedirectToAction("Index");
        }

        public ActionResult Detail(string id)
        {
            try
            {
                Guid conid = Guid.Parse(id);
                var dbo = StaticData.newsRepo.GetOne(a => a.NewsID == conid);
                var conv = NewsConverter.NewsTo(dbo);
                var role = Roles.GetRolesForUser();
                var censor = "";
                for (int i = 0; i < role.Length; i++)
                {
                    if (role[i] == "Censor" || role[i] == "censor")
                    {
                        censor = "Censor";
                    }
                }
                ViewData["censor"] = censor;
                return View(conv);
            }
            catch (Exception e)
            {
                return RedirectToAction("Error", "Admin");
            }
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Detail(NewsModel model, HttpPostedFileBase file, HttpPostedFileBase attach)
        {
            News dbo = new News();
            try
            {
                dbo = StaticData.newsRepo.GetOne(a => a.NewsID == model.NewsID);
            }
            catch (Exception e)
            {
                return RedirectToAction("Error", "Admin");
            }
            var copy = NewsConverter.CopyNews(dbo);

            if (string.IsNullOrEmpty(model.Avatar))
            {
                if (file != null)
                {
                    var legal = file.ContentType == "image/jpeg" || file.ContentType == "image/png" || file.ContentType == "image/gif" || file.ContentType == "image/jpg";
                    if (legal)
                    {
                        ServerHelper.DeleteFileOnServer(dbo.Avatar);
                        string time = PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                        string newName = time + "-" + file.FileName;
                        string path = "/Application_Data/Images/NewsImages/";
                        ServerHelper.SaveFileBaseOnServer(path, file, newName);
                        copy.Avatar = path + newName;
                    }
                }
                else
                {
                    copy.Avatar = "";
                    ServerHelper.DeleteFileOnServer(dbo.Avatar);
                }
            }
            else
            {
                if (dbo.Avatar != model.Avatar)
                    ServerHelper.DeleteFileOnServer(dbo.Avatar);
                copy.Avatar = model.Avatar;
            }
            var removeset = ServerHelper.NotExistFileName(ServerHelper.SplitFileName(dbo.AttachFiles), ServerHelper.SplitFileName(model.AttachFiles));
            foreach (var item in removeset)
            {
                ServerHelper.DeleteFileOnServer(item);
            }
            copy.AttachFiles = model.AttachFiles;
            if (attach != null)
            {
                string time = "pnco-" + PNLibraries.PNConvertToTimestamp(DateTime.Now).ToString();
                string newName = time + "-" + attach.FileName;
                string path = "/Application_Data/Files/NewsAttach/";
                ServerHelper.SaveFileBaseOnServer(path, attach, newName);
                copy.AttachFiles = copy.AttachFiles + path + newName + "*$*";
            }

            copy.Title = model.Title;
            copy.TLink = PNLibraries.PNChuyenKhongDau(model.Title);
            copy.Short = model.Short;
            copy.CType = 1;
            copy.Lang = model.Lang;
            copy.CommentAllow = model.CommentAllow;
            copy.ContentVN = model.ContentVN;
            StaticData.newsRepo.Save(dbo, copy);
            return RedirectToAction("Detail", new { id = copy.NewsID.ToString() });
        }

        public ActionResult Delete(string id)
        {
            try
            {
                Guid conid = Guid.Parse(id);
                var dbo = StaticData.newsRepo.GetOne(a => a.NewsID == conid);
                if (dbo != null)
                {
                    StaticData.newsRepo.Delete(dbo);
                    var attach = ServerHelper.SplitFileName(dbo.AttachFiles);
                    foreach (var item in attach)
                    {
                        ServerHelper.DeleteFileOnServer(item);
                    }
                    ServerHelper.DeleteFileOnServer(dbo.Avatar);
                }
            }
            catch (Exception e)
            {
            }
            return RedirectToAction("Index");
        }

    }
}
